<template>
  <div>
    <FormPanel ref="from" :list="formList" @formChange="changeHandle" :isSubmitBtn="false" :collapse="false"
               :labelWidth="190"></FormPanel>

    <FilterTable ref="table"
                 :columns="columns"
                 :dataSource="tableList"
                 height="auto"
                 :onColumnsChange="(columns) => (this.columns = columns)"
                 :onRowSelectChange="selectChangeHandle">
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" @click="addHandle()" icon="el-icon-plus">新 增</multiuse-button>
        <multiuse-button size="small" type="primary" @click="delHandle()" icon="el-icon-remove-outline">删 除
        </multiuse-button>
      </template>
    </FilterTable>

    <BaseDialog :visible.sync="isaddCar" :width="'80%'" :title="'选择车辆'" destroyOnClose
                :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addCar :orderData="orderData" @close="carcloseHandler"/>
    </BaseDialog>

    <div style="height: 47px"></div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right',
      }"
    >
      <el-button @click="closeDrawer(1)">关 闭</el-button>
      <multiuse-button type="primary" :click="closeDrawer.bind(this, 2)" :disabled="isSave">提 交</multiuse-button>
      <multiuse-button type="primary" :click="closeDrawer.bind(this, 3)" :disabled="isSave">保 存</multiuse-button>
    </div>
  </div>
</template>
<script>

import {
  getAmount,
  getDealerAddress,
  getDetail,
  getFiAccountType,
  getOrderDetailAmount,
  getOrderDetailType,
  saveOrder
} from '@/api/dealerSaleP/OrderManagement/OrderSubmission/index.js';
import {dictionary} from '@/utils/dictMixin';
import Cookies from 'js-cookie';
import selectCar from './selectCar';
import addCar from './addCar';
import moment from 'moment';

export default {
  mixins: [dictionary],
  components: {
    selectCar,
    addCar,
  },
  props: ['rowData'],
  data() {
    this.saveData = null;
    return {
      formList: this.createdFrom(),
      columns: this.createdTable(),
      tableList: [],
      isaddCar: false,
      orderData: {},
      json: {},
      dealerCode: Cookies.get('ownerCode'),
      isSave: false,
      accountTypeList: [],
      addressList: [],
      selectList: [],
      isDisabled: true
    };
  },
  created() {
    // 初始化
    this.initOrder();
  },
  mounted() {
    this.table = this.$refs.table.$refs.pageTable;
  },
  methods: {
    createdFrom() {
      return [
        {
          type: 'BREAK_SPACE',
          label: '订单信息',
        },
        {
          type: 'INPUT',
          label: '订单编号',
          fieldName: 'orderNo',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'DATE',
          label: '订单年月',
          fieldName: 'orderYearMonth',
          disabled: true,
          placeholder: '请输入',
          dateType: 'month',
          initialValue: moment().format('YYYY-MM'),
        },
        {
          type: 'INPUT',
          label: '订单经销商',
          fieldName: 'orderDealer',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'SELECT',
          label: '订单类型',
          fieldName: 'orderType',
          disabled: true,
          placeholder: '请选择',
          itemList: this.createDictList('2105'),
          initialValue: 21051002, // 默认增补订单
        },
        {
          type: 'SELECT',
          label: '订单细分类型',
          fieldName: 'orderDetailType',
          placeholder: '请选择',
          itemList: [],
        },
        {
          type: 'SELECT',
          label: '订单状态',
          fieldName: 'orderStatus',
          disabled: true,
          placeholder: '请选择',
          itemList: this.createDictList('2104'),
          initialValue: 21041001, // 默认新建
        },
        {
          type: 'SELECT',
          label: '订单紧急度',
          fieldName: 'emergencyType',
          placeholder: '请选择',
          itemList: this.createDictList('2101'),
          initialValue: 21011001,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
        },
        {
          type: 'SELECT',
          label: '运输方式',
          fieldName: 'transportType',
          placeholder: '请选择',
          itemList: this.createDictList('2409'),
          initialValue: 24091001,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
        },
        {
          type: 'SELECT',
          label: '收车地址',
          fieldName: 'addressId',
          placeholder: '请选择',
          itemList: [],
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          change: (value) => {
            this.orderAddressOnChange(value);
          },
        },
        {
          type: 'INPUT',
          label: '送达城市',
          fieldName: 'orderCity',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'linkMan',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '联系电话',
          fieldName: 'linkPhone',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          initialValue: 0.00,
          label: '资金可用余额',
          fieldName: 'totalFuelAmount',
          placeholder: '请选择',
          disabled: true,
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          initialValue: 0.00,
          label: '返利池可用余额',
          fieldName: 'singleRebateFuelAmount',
          disabled: true,
        },
        {
          type: 'INPUT_NUMBER',
          precision: 2,
          initialValue: 0.00,
          label: '本单返利使用金额',
          fieldName: 'singleRebateFuelTotalAmount',
          disabled: true,
        },
        {
          type: 'INPUT_NUMBER',
          label: '实付总金额',
          fieldName: 'realPayTotalAmount',
          precision: 2,
          initialValue: 0.00,
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '创建人',
          fieldName: 'createdName',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '创建时间',
          fieldName: 'createdAt',
          placeholder: '请输入',
          disabled: true,
        },
        {
          type: 'BREAK_SPACE',
          label: '车辆信息',
        },
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '物料编码',
          dataIndex: 'productCode',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '物料描述',
          dataIndex: 'productName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '提报数量',
          dataIndex: 'orderNum',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: 100,
          editable: true,
          editType: 'number',
          editRequired: true,
          defaultEditable: true,
          editPattern: /^[1-9]\d*$/,
          summation: true,
          rules: [{required: true, message: '请填写正整数', trigger: 'blur'}],
          onInput: (index, data) => {
            this.changeNum(index, data);
          },
        },
        {
          title: '车辆用途',
          dataIndex: 'vehicleUse',
          width: 150,
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('2102'),
          editable: true,
          editType: 'select',
          editRequired: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.vehicleUse}
                placeholder="请选择"
                onChange={(value) => {
                  p.row.vehicleUse = value;
                  this.reComputedAmount();
                }}
              >
                {this.createDictList('2102').map((item) => (
                  <el-option key={item.value} label={item.text} value={item.value}/>
                ))}
              </el-select>
            );
          },
        },
        {
          title: '资金类型',
          dataIndex: 'fundType',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          editType: 'select',
          editRequired: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.fundType}
                required
                placeholder="请选择"
                onChange={(value) => {
                  p.row.fundType = value;
                }}
              >
                {this.accountTypeList.map((item) => (
                  <el-option key={item.accountTypeId} label={item.accountTypeName} value={item.accountTypeId}/>
                ))}
              </el-select>
            );
          },
        },
        {
          title: '采购价格',
          dataIndex: 'afterDiscountAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '市场指导价',
          dataIndex: 'singleAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '现金折让',
          dataIndex: 'discountAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '建店返利',
          dataIndex: 'buildRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '是否使用返利',
          dataIndex: 'isRebate',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          editable: false,
          editType: 'select',
          editRequired: true,
          rules: [{required: true, message: '请选择', trigger: 'change'}],
          render: (p) => {
            return (
              <el-select
                size="mini"
                v-model={p.row.isRebate}
                placeholder="请选择"
                disabled={p.row.isRebateDisabled}
                onChange={(value) => {
                  p.row.isRebate = value;
                  this.reComputedAmount();
                }}
              >
                {this.createDictList('1004').map((item) => (
                  <el-option key={item.value} label={item.text} value={item.value}/>
                ))}
              </el-select>
            );
          },
        },
        {
          title: '返利池返利',
          dataIndex: 'singleRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'seriesName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '车型',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '配置',
          dataIndex: 'packageName',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '选装',
          dataIndex: 'optionName',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '内饰',
          dataIndex: 'trimName',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
        },
        {
          title: '外饰',
          dataIndex: 'colorName',
          align: 'center',
          sorter: true,
          filter: true,
          filterType: 'input',
        }
      ];
    },
    changeHandle(val) {
      this.saveData = val;
    },
    /**
     * 初始化
     * @returns {Promise<void>}
     */
    async initOrder() {
      this.isSave = true;
      // 判断是否编辑
      if (this.rowData) {
        // 通过订单id查询订单和订单明细数据
        let res = await getDetail({orderId: this.rowData.orderId});
        if (res.resultCode === 200) {
          for (let i in res.data) {
            this.formList.map(x => {
              if (i === x.fieldName) {
                x.initialValue = res.data[i];
              }
            });
          }

          this.tableList = res.data.detailDTOList || [];
          let orderAmountDatas = await getOrderDetailAmount(this.dealerCode, this.tableList);
          if (orderAmountDatas.resultCode === 200) {
            this.tableList.forEach(car => {
              const orderAmount = orderAmountDatas.data.find(({productCode}) => productCode === car.productCode);
              if (orderAmount) {
                car.orderAmount = orderAmount;
              }
            });
          }
        }
      }
      // 订单细分类型
      await this.getOrderDetailType();
      // 收车地址
      await this.getDealerAddress();
      // 经销商资金
      await this.getAmountDetail();
      // 资金类型
      await this.getFiAccountType();
      this.isSave = false;
    },
    /**
     * 获取订单细分类型
     */
    async getOrderDetailType() {
      let res = await getOrderDetailType({isAvailable: 10041001});
      if (res.resultCode === 200) {
        this.formList.map((x) => {
          if (x.fieldName === 'orderDetailType') {
            x.itemList = res.data.map((x) => ({text: x.subName, value: x.subId}));
          }
        });
      }
    },
    /**
     * 获取收车地址
     */
    async getDealerAddress() {
      let res = await getDealerAddress({dealerCode: this.dealerCode});
      if (res.resultCode === 200) {
        this.addressList = res.data;
        this.formList.map((x) => {
          if (x.fieldName === 'addressId') {
            x.itemList = this.addressList.map((x) => ({
              text: `${x.detaildAddress}${x.addressProperty === 60351001 ? '（主店）' : ''}`,
              value: x.addressId,
              addressProperty: x.addressProperty
            }));
          }
        });
      }
    },
    /**
     * 选择收车地址事件
     */
    async orderAddressOnChange(value) {
      this.addressList.map((addr) => {
        if (addr.addressId === value) {
          this.formList.find(item => item.fieldName === 'orderCity').initialValue = addr.cityName;
          this.formList.find(item => item.fieldName === 'linkMan').initialValue = addr.linkMan;
          this.formList.find(item => item.fieldName === 'linkPhone').initialValue = addr.linkPhone;
        }
      });
    },
    /**
     * 查询经销商资金可用余额和返利池可用余额
     */
    async getAmountDetail() {
      let res = await getAmount({dealerCode: this.dealerCode});
      if (res.resultCode === 200) {
        this.formList.find((x) => x.fieldName === 'totalFuelAmount').initialValue = res.data.totalFuelAmount;
        this.formList.find((x) => x.fieldName === 'singleRebateFuelAmount').initialValue = res.data.singleRebateFuelAmount;
      }
    },
    /**
     * 查询资金类型
     */
    async getFiAccountType() {
      let res = await getFiAccountType({dealerCode: this.dealerCode});
      if (res.resultCode === 200) {
        this.accountTypeList = res.data;
      }
    },
    /**
     * 选择车辆
     */
    addHandle() {
      this.$refs.from.SUBMIT_FORM();
      if (this.saveData) {
        // 主单数据
        let json = JSON.parse(JSON.stringify(this.saveData));
        json.dealerCode = this.dealerCode; // 经销商代码
        this.orderData = json;
        this.isaddCar = true;
        this.saveData = null;
      }
    },
    async carcloseHandler(carList, orderData) {
      this.isaddCar = false;
      this.saveData = null;
      if (carList) {
        let is = false;
        carList.map(car => {
          const obj = this.tableList.find(({productCode}) => productCode === car.productCode);
          if (obj) {
            is = true;
          }
        });
        if (!is) {
          await this.getDisecount(carList, orderData);
        } else {
          // 提示
          this.$notify({
            title: '警告',
            message: '不能重复添加相同车辆',
            type: 'warning'
          });
        }
      }
    },
    // 加载折扣信息
    async getDisecount(carData, orderData) {
      let orderAmountDatas = await getOrderDetailAmount(this.dealerCode, carData);
      if (orderAmountDatas.resultCode === 200) {
        carData.forEach(car => {
          const orderAmount = orderAmountDatas.data.find(({productCode}) => productCode === car.productCode);
          if (orderAmount) {
            car.orderAmount = orderAmount;
            // 提报数量
            car.orderNum = 1;
            // 车辆用途：默认客户订购
            car.vehicleUse = 21021001;
            // 资金类型：默认三方融资账户

            // 市场指导价
            car.singleAmount = car.oemDirectivePrice;
            // 是否使用返利：默认是
            car.isRebate = 10041001;
            this.table.EXECUTE_INSERT([car]);
          }
        });
      }
      // 计算价格
      this.reComputedAmount();
    },
    /**
     * 计算价格
     */
    reComputedAmount() {
      // 本单返利使用金额
      let singleRebateFuelTotalAmount = 0;
      // 实付总金额
      let realPayTotalAmount = 0;

      this.tableList.forEach(car => {
        // 建店返利
        car.buildRebateAmount = 0;
        car.buildRuleId = null;
        // 现金折让
        car.discountAmount = 0;
        car.discountRuleId = null;
        // 返利池返利
        car.singleRebateAmount = 0;

        if (car.vehicleUse === 21021001) {
          // 客户订购
          // 现金折让
          car.discountAmount = this.formatNumber(car.orderAmount.discountPrice);
          car.discountRuleId = car.orderAmount.discountRuleId;
          // 建店返利
          car.buildRebateAmount = this.formatNumber(car.orderAmount.buildDiscount);
          car.buildRuleId = car.orderAmount.buildRuleId;
          // 返利池返利, 是否返利为是：则取返利池金额，否则为0
          car.singleRebateAmount = this.formatNumber(car.isRebate === 10041001 ? car.orderAmount.rebatePrice : 0);
          // 采购价格=市场指导价-现金折让-建店返利-返利池返利
          car.afterDiscountAmount = this.formatNumber(car.singleAmount - car.discountAmount - car.buildRebateAmount - car.singleRebateAmount);
          car.afterDiscountAmount = this.formatNumber(car.afterDiscountAmount < 0 ? 0 : car.afterDiscountAmount);
          // 是否返利改改为是，取消禁用
          if (car.isRebateDisabled) {
            car.isRebate = 10041001;
            car.isRebateDisabled = false;
          }
        } else if (car.vehicleUse === 21021002) {
          // 试乘试驾：市场指导价*试乘试驾折扣比率
          car.afterDiscountAmount = this.formatNumber(car.orderAmount.tryDrivePrice < 0 ? 0 : car.orderAmount.tryDrivePrice);
          // 是否返利为改否，并禁用
          car.isRebate = 10041002;
          car.isRebateDisabled = true;
        } else if (car.vehicleUse === 21021003) {
          // 服务用车：采购价格=市场指导价*服务用车折扣比率
          car.afterDiscountAmount = this.formatNumber(car.orderAmount.serviceCarPrice < 0 ? 0 : car.orderAmount.serviceCarPrice);
          // 是否返利改为否，并禁用
          car.isRebate = 10041002;
          car.isRebateDisabled = true;
        } else if (car.vehicleUse === 21021004) {
          // 展车：采购价格=市场指导价*展车折扣比率
          car.afterDiscountAmount = this.formatNumber(car.orderAmount.displayCarPrice < 0 ? 0 : car.orderAmount.displayCarPrice);
          // 是否返利改为否，并禁用
          car.isRebate = 10041002;
          car.isRebateDisabled = true;
        }

        singleRebateFuelTotalAmount += this.formatNumber(car.singleRebateAmount * car.orderNum);
        realPayTotalAmount += this.formatNumber(car.afterDiscountAmount * car.orderNum);
      });

      this.formList.map(x => {
        if (x.fieldName === 'singleRebateFuelTotalAmount') {
          x.initialValue = this.formatNumber(singleRebateFuelTotalAmount);
        }
        if (x.fieldName === 'realPayTotalAmount') {
          x.initialValue = this.formatNumber(realPayTotalAmount);
        }
      });
    },
    changeNum(index, data) {
      let num = '';
      let str = '';
      for (let i in index) {
        num = index[i];
        str = i.split('|')[0];
      }
      let Rep = /^[1-9]\d*$/;
      if (num > 10000000000) {
        this.$notify({
          title: '警告',
          message: '输入数量过大',
          type: 'warning',
        });
        return;
      }
      if (Rep.test(num)) {
        this.reComputedAmount();
      }
    },
    /**
     * 删除选中车辆
     */
    async delHandle() {
      if (this.selectList.length === 0) {
        // 提示
        this.$notify({
          title: '警告',
          message: '请选择数据',
          type: 'warning'
        });
        return;
      }
      await this.$confirm('是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.selectList.forEach(data => {
          this.table.EXECUTE_DELETE([data]);
        })
        this.reComputedAmount();
      }).catch(() => {
      });
    },
    selectChangeHandle(rows) {
      this.selectList = rows;
    },
    async closeDrawer(type) {
      if (type === 1) {
        this.$emit('close');
      } else if (type === 2 || type === 3) {
        if (this.tableList.length < 1) {
          this.$notify({
            title: '警告',
            message: '请选择车辆',
            type: 'warning',
          });
          return;
        }

        this.$refs.from.SUBMIT_FORM();
        if (this.saveData) {
          let order = JSON.parse(JSON.stringify(this.saveData));
          if (this.rowData) {
            order = Object.assign({}, this.rowData, this.saveData);
          }
          let orderDetail = this.tableList;
          let is = false;
          orderDetail.map((x) => {
            if (Number(x.orderNum) > 10000000000 || Number(x.orderNum) < 1) {
              is = true;
            }
          });
          if (is) {
            this.$notify({
              title: '警告',
              message: '输入数量过大或过小',
              type: 'warning',
            });
            return;
          }
          order.detailDTOList = orderDetail;
          if (order.realPayTotalAmount > 1000000000) {
            this.$notify({
              title: '警告',
              message: '实付总金额或返利金额数额过大，请重新进行保存',
              type: 'warning',
            });
            return;
          }
          order.saveType = 'DLR';
          // 21041001:新建，21041002:已提报待审核
          order.orderStatus = type === 3 ? 21041001 : 21041002;
          order.orderMonth = order.orderYearMonth.split('-')[1];
          order.orderYear = order.orderYearMonth.split('-')[0];

          let res = await saveOrder(order);
          if (res.resultCode === 200) {
            this.$notify({
              title: '成功',
              message: '提交成功',
              type: 'success',
            });
            this.$emit('close', order);
          } else {
            this.saveData = null;
          }
        }
      }
    },
    changeValueNum(a) {
      if (!a || isNaN(a)) {
        return 0;
      } else {
        return a;
      }
    },
    formatNumber(val) {
      return Number(val).toFixed(2);
    },
  },
};
</script>
<style lang="less">
.discount {
  text-decoration: underline;
  color: #d1291a;
  cursor: pointer;
}
</style>
